import { useEffect, useState } from 'react';
import { Button, Form, Table, Input, Modal, Row, Col, DatePicker, message, Checkbox, InputNumber } from 'antd';
import WhillCheckInModel from './WhillCheckInModel';
import { GetRoomMsg } from '../service';
import moment from 'moment';
import StartIssuingCards from './StartIssuingCards';
import type { CheckboxProps, InputNumberProps } from 'antd';
import { useIntl, getLocale } from '@umijs/max';


interface drawerPrpos {
  drawerVisit: boolean,
  list2: RoomList[]
  setdrawerVisit: (event: boolean) => void
  setsendMsg: (event: stateObj) => void
  setType: (event: string) => void
  sendCardFlag: boolean
  setsendCardFlag: (Event: boolean) => void
  IfSendCard: boolean
  setGetcardMsg: (event: object) => void
}

const Addoccupants: React.FC<drawerPrpos> = ({ setGetcardMsg, IfSendCard, sendCardFlag, setsendCardFlag, setType, setsendMsg, list2, drawerVisit, setdrawerVisit }) => {
  const intl = useIntl()
  const currentLocale = getLocale();
  console.log("currentLocale", currentLocale)
  const [form] = Form.useForm();
  // 开始发卡弹窗状态
  const [StartFlag, setStartFlag] = useState(false)
  // Table列表中被选中当前列的下标
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[] | any>(); // 获取选中数据的下标 并且高亮
  // 记录结束时间传递到 开始发卡弹窗组件中 
  const [EndTimer, setEndTimer] = useState("")

  const [Formvalue, setFormvalue] = useState(0)
  // 验证表单 表单通过弹出开始发卡
  const handleSubmit = async () => {
    form.validateFields()
      .then((values): any => {
        if (!dataSource.length) return message.error("还未添加房间")

        setFormvalue(form.getFieldsValue())
        setStartFlag(true)
        setEndTimer(values.checkOutTimer.$d)


      })
      .catch((errorInfo) => {
        console.log('验证失败:', errorInfo);
      });
  };

  // 添加放假 
  const [WhillCheckInflag, setWhillCheckInflag] = useState(false)
  // 打开开始发卡
  const WhillCheckIn = () => {
    setWhillCheckInflag(true)
  }
  // Table列表渲染数据
  const [dataSource, setdataSource] = useState<RoomList[]>([])
  // 记录需要发多少张房卡
  const [dataSourceLength, setdataSourceLength] = useState(0)
  useEffect(() => {
    if (dataSource.length) {
      // 房间选完后 默认高亮第一条数据
      setSelectedRowKeys([dataSource[0].id])
      if (!StartFlag) {
        // 数组的长度只被记录一次  并传递给弹窗发卡组件 
        setdataSourceLength(dataSource.length)
      }
    }
  }, [dataSource])
  useEffect(() => {
    GETRoomMsg()
  }, [])
  // 发卡成功后进行的操作 同步删除已发房卡的数据
  useEffect(() => {
    if (sendCardFlag === true) {
      let Roomid: number = 0
      selectedRowKeys.forEach((element: number) => {
        Roomid = element
      });
      let arr = dataSource.filter((item: { id: number }) => item.id !== Roomid)
      setdataSource(arr)
      setsendCardFlag(false)

    } else {
      // 如何弹窗是打开状态且数组的长度为0 那么表示发卡已经结束 并关闭全部弹窗
      if (StartFlag) {
        if (!dataSource.length) {
          setStartFlag(false)
          Close()
        }
      }

    }
  }, [sendCardFlag])
  const [state, setState] = useState<stateObj>({
    T1: 0, // 默认加密
    T2: 0, // 默认加密
    T3: 0, // 默认加密
    T4: 0, // 覆写前卡
    T5: 0, // 超时报警
    T6: 0, // 静音
    T7: 0, // 反锁
    T8: 0,  // 其他状态
    day: "",
    TRoomTimer: ""
  });
  const [firstTwoDigits, setfirstTwoDigits] = useState()
  const GETRoomMsg = async () => {
    let { data } = await GetRoomMsg()
    let firstDigits: any
    if (data.defaultCheckoutTime) {
      firstDigits = data.defaultCheckoutTime.substring(0, 2);
      setfirstTwoDigits(firstDigits)
    }
    setState((prevState) => ({
      ...prevState,
      T1: data.defaultCardT1ReservedAlarm,
      T2: data.defaultCardT2ReservedAlarm,
      T3: data.defaultCardT3ReservedAlarm,
      T4: data.defaultCardT4EnableTheBeforeCardAlarm,
      T5: data.defaultCardT5GetPowerAlarm,
      T6: data.defaultCardT6TimeoutFalseLockAlarm,
      T7: data.defaultCardT7MuteAlarm,
      T8: data.defaultCardT8LockedAlarm,
      day: data.defaultCheckinDay,
      TRoomTimer: firstDigits
    }));
    let ChinkInday = isEmptyObject(data)?moment().add(1, 'days').startOf('day').add( 14, 'hours'):moment().add(data.defaultCheckinDay, 'days').startOf('day').add(firstDigits ? firstDigits : 14, 'hours')


    form.setFieldValue("checkOutTimer",ChinkInday)
    form.setFieldValue("checkInTimer", moment());
  }
  const columns = [
    {
      title: intl.formatMessage({id:"business.Building"}),
      dataIndex: 'bName',
    },
    {
      title:intl.formatMessage({id:"business.floor"}),
      dataIndex: 'floor',

    },
    {
      title: intl.formatMessage({id:"business.Room name"}),
      dataIndex: 'roomName',

    },
    {
      title: intl.formatMessage({id:"Room type"}),
      dataIndex: 'tName',
    },
    {
      title: intl.formatMessage({id:"business.Action"}),
      width: 50,
      dataIndex: 'operation',
      render: (_: any, record: {
        id: number
      }) =>
        dataSource.length >= 1 ? (
          <Button type='link' danger onClick={() => delRoom(record.id)}>{intl.formatMessage({id:"business.Delete"})}</Button>

        ) : null,
    },
  ];


  const delRoom = (id: number) => {

    let arr = dataSource.filter((item: RoomList) => {
      return item.id !== id
    })
    setdataSource(arr)
  }

  function isEmptyObject(obj: {}) {
    return typeof obj === 'object' && Object.keys(obj).length === 0;
  }
  const [Changebox, setChangebox] = useState(false)
  // const onChange: CheckboxProps['onChange'] = (e) => {
  //   setChangebox(e.target.checked)
  //   form.setFieldValue("checkInTimer", moment().add(1, 'days'));
  //   form.setFieldValue("checkOutTimer", moment().add(2, 'days').startOf('day').add(firstTwoDigits ? firstTwoDigits : 14, 'hours'));
  //   if (!e.target.checked) {
  //     form.setFieldValue("checkInTimer", moment());
  //     form.setFieldValue("checkOutTimer", moment().add(state.day, 'days').startOf('day').add(firstTwoDigits ? firstTwoDigits : 14, 'hours'));
  //     form.setFieldValue("InputNumber", 1);

  //   }
  // };
  const Close = () => {
    setdrawerVisit(false)
  }
  const onChangeNumber: InputNumberProps['onChange'] = (value) => {
    console.log("时间赋值",moment().add(Number(value) + 1, 'days').startOf('day').add(firstTwoDigits ? firstTwoDigits : 14, 'hours'));
    form.setFieldValue("checkOutTimer", moment().add(Number(value) + 1, 'days').startOf('day').add(firstTwoDigits ? firstTwoDigits : 14, 'hours'));
  };
  return (
    <>
      {
        StartFlag && <StartIssuingCards
          StartFlag={StartFlag}
          setStartFlag={setStartFlag}
          dataSource={dataSource}
          IfSendCard={IfSendCard}
          state={state}
          setsendMsg={setsendMsg}
          setType={setType}
          EndTimer={EndTimer}
          sendCardFlag={sendCardFlag}
          setsendCardFlag={setsendCardFlag}
          dataSourceLength={dataSourceLength}
          delRoom={delRoom}
          setGetcardMsg={setGetcardMsg}
          Formvalue={Formvalue}
          CloseAll={Close}
        />
      }
      {/* 添加房间 */}
      {
        WhillCheckInflag && <WhillCheckInModel
          WhillCheckInflag={WhillCheckInflag}
          setWhillCheckInflag={setWhillCheckInflag}
          list2={list2}
          dataSource={dataSource}
          setdataSource={setdataSource}

        />
      }
      <Modal
        title={intl.formatMessage({ id: "business.Checking in" })}
        open={drawerVisit}
        onCancel={Close}
        width={1000}
        footer={null}
        maskClosable={false}
      >
        <p style={{ margin: 30 }}> </p>
        <Form
          form={form}
        // layout={"vertical"}
        >

          <Row gutter={10}>
            <Col span={currentLocale == "zh-CN" ? 7 : 10}>
              <Form.Item
                name="checkIn"
                label={intl.formatMessage({ id: "business.Occupants" })}
                rules={[{ required: true, message: intl.formatMessage({ id: "business.Please enter the guest's name." }) }]}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              // initialValue={"张山"}
              >
                <Input placeholder={intl.formatMessage({ id: "business.Please enter the guest's name." })} style={{ width: 210 }} />
              </Form.Item>
            </Col>

            <Col span={currentLocale == "zh-CN" ? 7 : 10} offset={2}>
              <Form.Item
                name="phone"
                label={intl.formatMessage({ id: "business.Mobile" })}
                rules={[{ required: true, message: intl.formatMessage({ id: "business.Please enter Mobile." }) }]}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              // initialValue={"13800000000"}
              >
                <Input placeholder={intl.formatMessage({ id: "business.Please enter Mobile." })} style={{ width: 210 }} />
              </Form.Item>
            </Col>
            {/* <Col span={7} style={{ paddingLeft: 50 }}>
              <Form.Item
                name="change"
                label="预定入住"
              >
                <Checkbox value={false} onChange={onChange}></Checkbox>
              </Form.Item>
            </Col> */}
          </Row>
          <Row gutter={10}>
            <Col span={currentLocale == "zh-CN" ? 7 : 10}>
              <Form.Item
                name="checkInTimer"
                label={intl.formatMessage({ id: "business.Check-in time" })}
                rules={[{ required: true, message: intl.formatMessage({ id: "business.Please choose your check-in time." }) }]}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              >
                <DatePicker disabled={!Changebox} style={{ width: 210 }} showTime />
              </Form.Item>

            </Col>
            <Col span={currentLocale == "zh-CN" ? 7 : 10} offset={2}>
              <Form.Item
                name="checkOutTimer"
                label={intl.formatMessage({ id: "business.Check-out time" })}
                rules={[{ required: true, message: intl.formatMessage({ id: "business.Please select Check-out time" }) }]}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              >
                <DatePicker style={{ width: 210 }} showTime />
              </Form.Item>
            </Col>
            {
              Changebox && <Col span={7} style={{ paddingLeft: 50 }}>
                <Form.Item
                  name="InputNumber"
                  label={intl.formatMessage({ id: "business.Scheduled days" })}
                  initialValue={1}
                >
                  <InputNumber min={1} max={30} onChange={onChangeNumber} />
                </Form.Item>
              </Col>
            }

          </Row>
        </Form>

        <Table
          pagination={false}
          dataSource={dataSource}
          rowKey={(row) => row.id}
          columns={columns}
          bordered
          rowSelection={{
            type: 'radio',
            selectedRowKeys,
          }}
          onRow={(record) => ({
            onClick: () => {
              const newSelectedRowKeys = [record.id];
              setSelectedRowKeys(newSelectedRowKeys);
            },
          })}
          size='small'
        // scroll={{ y: 400,x:600}}

        />
        <br />
        <div>
          <Button onClick={WhillCheckIn} type="primary">{intl.formatMessage({ id: "business.Add room" })}</Button> &emsp;
          {/* <Button onClick={() => setdrawerVisit(false)}>取消</Button>   &emsp; */}
          <Button onClick={handleSubmit} type="primary">{intl.formatMessage({ id: "business.Issuing" })}</Button>
        </div>
      </Modal>

    </>
  )
}

export default Addoccupants


